package com.quick.android.handler.http;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


import android.text.TextUtils;
import android.util.Log;

public class HttpUrlConnectionHandler {
	/** 连接超时时间 */
	public static int mConnectionTimeout = 10 * 1000;
	/** 读取超时时间 */
	public static int mReadTimeout = 10 * 1000;

	public static String GET = "GET";
	public static String POST = "POST";

	public static HttpURLConnection getConnection(String url, String method) {
		try {
			URL mURL = new URL(url);
			HttpURLConnection con = (HttpURLConnection) mURL.openConnection();
			con.setConnectTimeout(mConnectionTimeout);
			con.setReadTimeout(mReadTimeout);
			if (TextUtils.isEmpty(method)) {
				method = GET;
			}
			con.setRequestMethod(method);
			if (method.equals(GET)) {

			} else {
				con.setDoInput(true);
				con.setDoOutput(true);
				con.setUseCaches(false);
			}
			return con;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void get() {
		String url = "http://www.baidu.com";
		try {
			HttpURLConnection con = getConnection(url, GET);
			if (con == null) {
				return;
			}
			InputStream in = con.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			StringBuilder sb = new StringBuilder();
			String readline = null;
			while ((readline = br.readLine()) != null) {
				sb.append(readline);
			}
			in.close();
			br.close();
			con.disconnect();
			Log.e("HttpUrlConnectionHandler", "get:" + sb.toString());
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void post() {
		String url = "";
		try {
			HttpURLConnection con = getConnection(url, POST);
			// 上传参数 格式"username="+username+"&password="+password
			DataOutputStream out = new DataOutputStream(con.getOutputStream());
			String content = "";
			out.writeBytes(content);
			out.flush();
			out.close();

			InputStream in = con.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			StringBuilder sb = new StringBuilder();
			String readline = null;
			while ((readline = br.readLine()) != null) {
				sb.append(readline);
			}
			in.close();
			br.close();
			con.disconnect();
			Log.e("HttpUrlConnectionHandler", "get:" + sb.toString());
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
